<template>
  <div class="user-role-container">
    <!-- 页面标题和搜索区域 -->
    <div class="page-header">
      <h1>用户角色分配</h1>
      <p>管理系统用户及其角色权限，确保合适的人员拥有合适的访问权限</p>
      
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入用户名、邮箱或手机号"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
        
        <div class="operation-buttons">
          <el-button type="primary" icon="el-icon-plus" @click="openAddUserDialog">
            新增用户
          </el-button>
          <el-button icon="el-icon-refresh" @click="refreshData">
            刷新
          </el-button>
          <el-button icon="el-icon-refresh" @click="refreshData">
            导入
          </el-button>
          <el-button icon="el-icon-refresh" @click="refreshData">
            导出
          </el-button>
        </div>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="user-table">
      <el-table
        :data="users"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="头像" width="80">
          <template slot-scope="scope">
            <el-avatar 
              :size="40" 
              :src="getAvatarUrl(scope.row.avatar)"
              :alt="scope.row.username"
            >
              <i class="el-icon-user" v-if="!scope.row.avatar"></i>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="220"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column prop="department" label="部门" width="150"></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <div class="status-badge">
              <span class="status-dot" :class="scope.row.status === 'active' ? 'status-active' : 'status-inactive'"></span>
              {{ scope.row.status === 'active' ? '激活' : '禁用' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="200">
          <template slot-scope="scope">
            <div>
              <el-tag
                v-for="role in scope.row.roles"
                :key="role.id"
                class="role-tag"
                :type="getRoleTagType(role.id)"
                closable
                @close="removeRole(scope.row, role.id)"
              >
                {{ role.name }}
              </el-tag>
              <el-button
                type="primary"
                text
                icon="el-icon-plus"
                size="small"
                @click="openAssignRoleDialog(scope.row)"
              >
                分配角色
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              text
              size="small"
              @click="editUser(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              text
              size="small"
              @click="deleteUser(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[4, 8, 10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers"
      ></el-pagination>
    </div>

    <!-- 分配角色对话框 -->
    <el-dialog
      :title="`为用户 ${selectedUser ? selectedUser.username : ''} 分配角色`"
      :visible.sync="assignRoleDialogVisible"
      width="500px"
    >
      <div>
        <p style="margin-bottom: 15px;">当前角色：</p>
        <div style="margin-bottom: 20px;">
          <el-tag
            v-for="role in selectedUser ? selectedUser.roles : []"
            :key="role.id"
            class="role-tag"
            :type="getRoleTagType(role.id)"
            closable
            @close="removeRole(selectedUser, role.id)"
          >
            {{ role.name }}
          </el-tag>
        </div>
        
        <p style="margin-bottom: 15px;">可选角色：</p>
        <el-checkbox-group v-model="selectedRoleIds">
          <div style="display: flex; flex-direction: column; gap: 12px;">
            <el-checkbox
              v-for="role in availableRoles"
              :key="role.id"
              :label="role.id"
            >
              {{ role.name }}
              <el-tag
                :type="getRoleTagType(role.id)"
                size="small"
                style="margin-left: 8px;"
              >
                {{ role.level }}
              </el-tag>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="assignRoles">确认分配</el-button>
      </div>
    </el-dialog>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="isEditing ? '编辑用户' : '新增用户'"
      :visible.sync="userDialogVisible"
      width="500px"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="80px"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9527/api/system/user/avatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
            :data="uploadData"
          >
            <img v-if="userForm.avatar" :src="getAvatarUrl(userForm.avatar)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="userForm.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditing">
          <el-input type="password" v-model="userForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password1" v-if="!isEditing">
          <el-input type="password" v-model="userForm.password1" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="userForm.department" placeholder="请选择部门" style="width: 100%">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">激活</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, saveRolesByUserId, deleteRoleIdByUserId, insert, deleteById, avatarUp} from '@/api/user'
import { getRoles } from '@/api/role'
import { deptAll } from '@/api/dept'

export default {
  name: 'UserRoleManagement',
  data() {
    // 密码验证规则
    const validatePass = (rule, value, callback) => {
      if (!this.isEditing && !value) {
        callback(new Error('请输入密码'))
      } else {
        if (this.userForm.password1 !== '') {
          this.$refs.userFormRef.validateField('password1')
        }
        callback()
      }
    }
    
    const validatePass1 = (rule, value, callback) => {
      if (!this.isEditing && !value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    
    return {
      // 搜索关键词
      searchKeyword: '',
      
      // 分页相关
      currentPage: 1,
      pageSize: 5,
      totalUsers: 0,
      
      // 加载状态
      loading: false,
      
      // 用户列表数据
      users: [],
      
      // 对话框控制
      assignRoleDialogVisible: false,
      userDialogVisible: false,
      isEditing: false,
      
      // 选中的用户
      selectedUser: null,
      
      // 选中的角色ID
      selectedRoleIds: [],

         //新增和编辑上传用户ID，传图片用
      uploadData:{
          userId: ''  // 用于上传时传递用户ID
      },
      
      // 用户表单
      userForm: {
        id: '',
        username: '',
        age: '',
        password: '',
        password1: '',
        email: '',
        phone: '',
        department: '',
        status: 'active',
        avatar: '',
        updateOrSave: true
      },
      
      // 表单验证规则
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        password1: [
          { validator: validatePass1, trigger: 'blur' }
        ]
      },
      
      // 部门选项
      departments: [],
      
      // 可用角色
      availableRoles: [],
      
      // 上传请求头
      uploadHeaders: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    }
  },
  
  mounted() {
    this.getList()
    this.deptAll()
  },
  
  methods: {
    // 获取用户列表
    async getList() {
      this.loading = true
      let PageParam = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        totalUsers: this.totalUsers,
        searchKeyword: this.searchKeyword
      }
      try {
        const res = await getList(PageParam)
        if (res.code === 200) {
          this.users = res.data.records
          this.totalUsers = res.data.total
        } else {
          this.$message.error(res.message || '获取用户列表失败')
        }
      } catch (error) {
        this.$message.error('获取用户列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    
    // 获取部门列表
    async deptAll() {
      try {
        const res = await deptAll()
        if (res.code === 200) {
          this.departments = res.data
        } else {
          this.$message.error(res.message || '获取部门列表失败')
        }
      } catch (error) {
        this.$message.error('获取部门列表失败')
        console.error(error)
      }
    },
    
    // 获取角色列表
    async getRoles() {
      try {
        const res = await getRoles()
        if (res.code === 200) {
          this.availableRoles = res.data
        } else {
          this.$message.error(res.message || '获取角色列表失败')
        }
      } catch (error) {
        this.$message.error('获取角色列表失败')
        console.error(error)
      }
    },
    
    // 处理搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },
    
    // 刷新数据
    refreshData() {
      this.getList()
      this.$message({
        message: '数据已刷新',
        type: 'success'
      })
    },
    
    // 打开分配角色对话框
    openAssignRoleDialog(user) {
      this.selectedUser = user
      this.selectedRoleIds = user.roles.map(role => role.id)
      this.getRoles()
      this.assignRoleDialogVisible = true
    },
    
    // 分配角色
    async assignRoles() {
      if (!this.selectedUser) return
      
      try {
        const data = {
          id: this.selectedUser.id,
          Roles: this.availableRoles
            .filter(role => this.selectedRoleIds.includes(role.id))
            .map(role => ({ id: role.id, name: role.name }))
        }
        
        const res = await saveRolesByUserId(data)
        if (res.code === 200) {
          this.assignRoleDialogVisible = false
          this.getList()
          this.$message({
            message: '角色分配成功',
            type: 'success'
          })
        } else {
          this.$message.error(res.message || '角色分配失败')
        }
      } catch (error) {
        this.$message.error('角色分配失败')
        console.error(error)
      }
    },
    
    // 移除角色
    async removeRole(user, roleId) {
      try {
        const res = await deleteRoleIdByUserId(user.id, roleId)
        if (res.code === 200) {
          this.getList()
          this.$message({
            message: '角色删除成功',
            type: 'success'
          })
        } else {
          this.$message.error(res.message || '角色删除失败')
        }
      } catch (error) {
        this.$message.error('角色删除失败')
        console.error(error)
      }
    },
    
    // 获取角色标签类型
    getRoleTagType(roleId) {
      const types = ['', 'success', 'info', 'warning', 'danger']
      return types[roleId % types.length]
    },
    
    // 打开添加用户对话框
    openAddUserDialog() {
      this.isEditing = false
      this.userForm = {
        id: '',
        username: '',
        age: '',
        password: '',
        password1: '',
        email: '',
        phone: '',
        department: '',
        status: 'active',
        avatar: '',
        updateOrSave: true
      }
      this.userDialogVisible = true
      
      // 清除表单验证
      if (this.$refs.userFormRef) {
        this.$refs.userFormRef.clearValidate()
      }
    },
    
    // 编辑用户
    editUser(user) {
      this.isEditing = true
      this.userForm = { ...user }
        // 编辑用户时设置userId
      this.uploadData.userId = user.id
      this.userDialogVisible = true
      
      // 清除表单验证
      if (this.$refs.userFormRef) {
        this.$refs.userFormRef.clearValidate()
      }
    },
    
    // 保存用户
    async saveUser() {
      this.$refs.userFormRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.isEditing) {
              this.userForm.updateOrSave = false
            } else {
              this.userForm.updateOrSave = true
              if (this.userForm.password !== this.userForm.password1) {
                this.$message({
                  message: '两次输入密码不一致',
                  type: 'error'
                })
                return
              }
            }
            
            const res = await insert(this.userForm)
            if (res.code === 200) {
              this.getList()
              this.userDialogVisible = false
              this.$message({
                message: this.isEditing ? '用户信息已更新' : '用户添加成功',
                type: 'success'
              })
            } else {
              this.$message.error(res.message || '保存用户失败')
            }
          } catch (error) {
            this.$message.error('保存用户失败')
            console.error(error)
          }
        } else {
          this.$message({
            message: '请检查表单填写是否正确',
            type: 'error'
          })
          return false
        }
      })
    },
    
    // 删除用户
    deleteUser(user) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteById(user.id)
          if (res.code === 200) {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
          console.error(error)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getList()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    
    // 头像上传成功
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        console.log("res===",res)
        this.userForm.avatar = res.data
        this.$message({
          message: '头像上传成功',
          type: 'success'
        })
      } else {
        this.$message.error(res.message || '头像上传失败')
      }
    },
    
    // 头像上传前校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    
    // 获取头像URL
    getAvatarUrl(avatar) {
      if (!avatar) return ''
      if (avatar.startsWith('http')) return avatar
      return `/api/uploads/avatars/${avatar}`
    }
  }
}
</script>

<style scoped>
.user-role-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 20px;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.user-table {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.role-tag {
  margin: 2px 4px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.status-badge {
  display: inline-flex;
  align-items: center;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-active {
  background-color: #67c23a;
}

.status-inactive {
  background-color: #f56c6c;
}

/* 头像上传样式 */
.avatar-uploader {
  display: block;
  text-align: center;
}

.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  margin: 0 auto;
}

.avatar-uploader >>> .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>